package com.kzj.mls.recyclerCard.cardView;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.PayTask;
import com.kzj.mls.R;
import com.kzj.mls.activity.ChooseTimeActivity;
import com.kzj.mls.activity.GBaseActivity;
import com.kzj.mls.activity.SelectAddressActivity;
import com.kzj.mls.activity.SelectStoreActivity;
import com.kzj.mls.activity.ServiceOrderActivity;
import com.kzj.mls.alibabaPay.PayResult;
import com.kzj.mls.alibabaPay.SignUtils;
import com.kzj.mls.beans.AliPayBean;
import com.kzj.mls.beans.CloseActivityBean;
import com.kzj.mls.beans.OrderBean;
import com.kzj.mls.beans.ServiceBookBean;
import com.kzj.mls.beans.WeiXinPayBean;
import com.kzj.mls.global.App;
import com.kzj.mls.global.Constant;
import com.kzj.mls.recyclerCard.basic.CardItemView;
import com.kzj.mls.recyclerCard.card.service.ServiceOrderCard;
import com.kzj.mls.request.BaseResponse;
import com.kzj.mls.request.ICallBackForRequestServer;
import com.kzj.mls.request.RequestServerManager;
import com.kzj.mls.util.ImageUtil;
import com.kzj.mls.util.WeiXinUtil;
import com.kzj.mls.wxapi.WXPayEntryActivity;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.io.Serializable;
import java.net.URLEncoder;
import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;

import de.greenrobot.event.EventBus;


public class ServiceOrderCardView extends CardItemView<ServiceOrderCard> {
    private Context mContext;
    private RelativeLayout relativeLayoutBottom;
    private ImageView imageView_product;
    private TextView textView_product_title;
    private TextView textView_product_price;
    private TextView textView_pay;
    private EditText editText_user_tel, editText_user_name;
    private TextView textView_store;
    private TextView textView_home_address;
    private TextView textView_service_time;
    private TextView textView_coupon;
    private TextView textView_product_total;
    private TextView textViewZhiFuBao;
    private TextView textViewWeiXin;
    private TextView textView_desc_store;
    private TextView textView_desc_home_address;
    private ImageView imageView_store;
    private ImageView imageView_address;
    private RelativeLayout relativeLayout_store;
    private RelativeLayout relativeLayout_address;
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;
    public static final String payTypeAlipay = "alipay";
    public static final String payTypeWeiXinpay = "weixin";
    private String payType = payTypeAlipay;
    public static final String serviceSiteTypeShangMen = "1";
    public static final String serviceSiteTypeDaoDian = "2";
    public static String serviceSiteType = serviceSiteTypeDaoDian;
    private TextView textView_store_address;
    public static String order_id;
    public static String order_detailed;
    public static String PayFlag;
    public static String thisFlag = "ServiceOrderCardView";

    public ServiceOrderCardView(Context context) {
        super(context);

        mContext = context;
        // TODO Auto-generated constructor stub
    }

    public ServiceOrderCardView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        // TODO Auto-generated constructor stub
    }

    public ServiceOrderCardView(Context context,
                                AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
        // TODO Auto-generated constructor stub
    }

    @Override
    public void build(final ServiceOrderCard card) {
        // TODO Auto-generated method stub
        super.build(card);
        relativeLayoutBottom = (RelativeLayout) findViewById(R.id.relativeLayoutBottom);
        imageView_product = (ImageView) findViewById(R.id.imageView_product);
        textView_product_title = (TextView) findViewById(R.id.textView_product_title);
        textView_product_price = (TextView) findViewById(R.id.textView_product_price);
        editText_user_name = (EditText) findViewById(R.id.editText_user_name);
        editText_user_tel = (EditText) findViewById(R.id.editText_user_tel);
        textView_store = (TextView) findViewById(R.id.textView_store);
        textView_home_address = (TextView) findViewById(R.id.textView_home_address);
        textView_service_time = (TextView) findViewById(R.id.textView_service_time);
        textView_coupon = (TextView) findViewById(R.id.textView_coupon);
        textView_product_total = (TextView) findViewById(R.id.textView_product_total);
        textViewZhiFuBao = (TextView) findViewById(R.id.textViewZhiFuBao);
        textViewWeiXin = (TextView) findViewById(R.id.textViewWeiXin);
        textView_desc_store = (TextView) findViewById(R.id.textView_desc_store);
        textView_desc_home_address = (TextView) findViewById(R.id.textView_desc_home_address);
        imageView_store = (ImageView) findViewById(R.id.imageView_store);
        imageView_address = (ImageView) findViewById(R.id.imageView_address);
        relativeLayout_address = (RelativeLayout) findViewById(R.id.relativeLayout_address);
        relativeLayout_store = (RelativeLayout) findViewById(R.id.relativeLayout_store);
        textView_pay = (TextView) findViewById(R.id.textView_pay);
        textView_store_address = (TextView) findViewById(R.id.textView_store_address);
        if (card.getServiceBookBean() != null) {
            ServiceBookBean.GoodsEntity goodsEntity = card.getServiceBookBean().getGoods();
            ServiceBookBean.UserinfoEntity userinfoEntity = card.getServiceBookBean().getUserinfo();

            textView_product_total.setText("总计：" + card.getServiceBookBean().getGoods().getPrice() + "元");
            //计算价格
            if (card.getServiceBookBean().getCoupon().size() != 0 && card.getCouponIndex() != -1) {
                BigDecimal couponValue = new BigDecimal(card.getServiceBookBean().getCoupon().get(card.getCouponIndex()).getCoupon_value());
                BigDecimal price = new BigDecimal(card.getServiceBookBean().getGoods().getPrice());
                if (price.subtract(couponValue).compareTo(BigDecimal.ZERO) == 0 || price.subtract(couponValue).compareTo(BigDecimal.ZERO) < 0) {
                    card.setPrice("0.01");
                } else
                    card.setPrice(price.subtract(couponValue) + "");
                textView_product_total.setText("总计：" + card.getServiceBookBean().getGoods().getPrice() + "-" + card.getServiceBookBean().getCoupon()
                        .get(card.getCouponIndex()).getCoupon_value() + "=" + card.getPrice() + "元");
            }

            //用户信息
            if (card.getServiceBookBean().getUserinfo().getReal_name() != null) {
                editText_user_name.setText(card.getServiceBookBean().getUserinfo().getReal_name());
            }
            if (card.getServiceBookBean().getUserinfo().getPhone_mob() != null) {
                editText_user_tel.setText(card.getServiceBookBean().getUserinfo().getPhone_mob());
            }
            editText_user_tel.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    card.getServiceBookBean().getUserinfo().setPhone_mob(s.toString());
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });

            //商品名称价钱
            if (goodsEntity != null) {
                textView_product_title.setText(goodsEntity.getGoods_name());
                textView_product_price.setText("¥" + goodsEntity.getPrice());
                App.displayImageHttpOrFile(goodsEntity.getDefault_image(), imageView_product, ImageUtil.OptionsNormal());
            }
            //优惠劵
            if (card.getServiceBookBean().getCoupon() != null && card.getServiceBookBean().getCoupon().size() != 0) {
                if (card.getCouponIndex() != -1) {
                    if (!TextUtils.isEmpty(card.getServiceBookBean().getCoupon().get(card.getCouponIndex()).getCoupon_name())) {
                        textView_coupon.setText(card.getServiceBookBean().getCoupon().get(card.getCouponIndex()).getCoupon_name());
                    }
                } else {
                    textView_coupon.setText("不使用优惠劵");
                }
            } else {
                textView_coupon.setText("无可用优惠劵");
            }
            //服务方式地址
            if (null != card.getServiceBookBean().getService_addr() && card.getServiceBookBean().getService_addr().size() > 0) {
                textView_store.setText(card.getServiceBookBean().getService_addr().get(0).getStore_name());
                textView_store_address.setText(card.getServiceBookBean().getService_addr().get(0).getService_address());
            } else {
                textView_store.setText("暂无提供服务的店面");
                textView_store_address.setVisibility(GONE);
            }
            //上门地址
            textView_home_address.setText("请选择上门地址");
            if (card.getServiceBookBean().getAddr() != null && card.getServiceBookBean().getAddr().size() > 0) {
                for (int i = 0; i < card.getServiceBookBean().getAddr().size(); i++) {
                    if (card.getServiceBookBean().getAddr().get(i).getIs_default().equals("1")) {
                        textView_home_address.setText(card.getServiceBookBean().getAddr().get(i).getAddress());
                        break;
                    }
                }
            }
//               String date = card.getServiceBookBean().getBooking_date().get(card.getDateIndex());
//              String time = card.getServiceBookBean().getBooking_time().get(card.getTimeIndex()).get(0);

            textView_service_time.setText(card.getBookDateTime().getBooking_date() + " " + card.getBookDateTime().getBooking_time());
            textView_service_time.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getContext(), ChooseTimeActivity.class);
                    intent.putExtra(ServiceOrderActivity.TagSID, card.getSid());
                    intent.putExtra(ChooseTimeActivity.bookDateTimeTag, (Serializable) card.getBookDateTime());
                    intent.putExtra(ChooseTimeActivity.TagDateList, (Serializable) card.getServiceBookBean().getBooking_date());
                    intent.putExtra(ChooseTimeActivity.TagTimeList, (Serializable) card.getServiceBookBean().getBooking_time());
                    getContext().startActivity(intent);
                }
            });
            textViewWeiXin.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Drawable drawable = getResources().getDrawable(R.drawable.icon_correct);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
                    textViewWeiXin.setCompoundDrawables(null, null, drawable, null);//画在右边
                    textViewZhiFuBao.setCompoundDrawables(null, null, null, null);//画在右边
                    payType = payTypeWeiXinpay;
                }
            });
            textViewZhiFuBao.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Drawable drawable = getResources().getDrawable(R.drawable.icon_correct);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
                    textViewWeiXin.setCompoundDrawables(null, null, null, null);//画在右边
                    textViewZhiFuBao.setCompoundDrawables(null, null, drawable, null);//画在右边
                    payType = payTypeAlipay;
                }
            });
            textView_coupon.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    card.getOnNormalButtonPressedListener().onButtonPressedListener(v, card);
                }
            });
            if (serviceSiteType == serviceSiteTypeDaoDian) {
                imageView_store.setImageResource(R.drawable.icon_correct);
                imageView_address.setImageBitmap(null);
            } else if (serviceSiteType == serviceSiteTypeShangMen) {
                imageView_address.setImageResource(R.drawable.icon_correct);
                imageView_store.setImageBitmap(null);
            }
            relativeLayout_store.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    imageView_store.setImageResource(R.drawable.icon_correct);
                    imageView_address.setImageBitmap(null);
                    Intent intent = new Intent(mContext, SelectStoreActivity.class);
                    intent.putExtra("service_addr", (Serializable) card.getServiceBookBean().getService_addr());
                    mContext.startActivity(intent);
                    serviceSiteType = serviceSiteTypeDaoDian;
                }
            });
            relativeLayout_address.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    imageView_address.setImageResource(R.drawable.icon_correct);
                    imageView_store.setImageBitmap(null);
                    Intent intent = new Intent(mContext, SelectAddressActivity.class);
                    intent.putExtra("beans", card.getServiceBookBean());
                    mContext.startActivity(intent);
                    serviceSiteType = serviceSiteTypeShangMen;
                }
            });
            textView_pay.setOnClickListener(new OnClickListener() {
                String homeAddressID;
                String coupon_id = "-1";

                @Override
                public void onClick(View v) {

                    for (ServiceBookBean.HomeAddressEntity homeAddressEntity : card.getServiceBookBean().getAddr()) {
                        if (homeAddressEntity.getIs_default().equals("1")) {
                            homeAddressID = homeAddressEntity.getAddr_id();
                        }
                    }
                    if (card.getCouponIndex() == -1) {
                        coupon_id = "-1";
                    } else {
                        if (card.getServiceBookBean().getCoupon() != null && card.getServiceBookBean().getCoupon().size() > 0)
                            coupon_id = card.getServiceBookBean().getCoupon().get(card.getCouponIndex()).getCoupon_id();
                    }

                    String service_addr = "";
                    if (card.getServiceBookBean().getService_addr().size() > 0) {
                        service_addr = card.getServiceBookBean().getService_addr().get(0).getStore_id();
                    }
                    if (serviceSiteType.equals(serviceSiteTypeShangMen)) {
                        if (homeAddressID == null || homeAddressID.equals("")) {
                            App.showToast("请设置上门地址");
                            return;
                        }
                    }else{
                        if (service_addr.equals("")){
                            App.showToast("请选择服务店面/或选择上门服务");
                            return;
                        }
                    }
                    if (editText_user_name.getText() == null || editText_user_name.getText().toString().equals("")) {
                        App.showToast("请填写用户姓名");
                        return;
                    }
                    TaskCreateOrderID(card.getSid(), editText_user_name.getText().toString(), editText_user_tel.getText().toString(),
                            card.getBookDateTime().getBooking_date(), card.getBookDateTime().getBooking_time(),
                            serviceSiteType, homeAddressID, service_addr, coupon_id,
                            payType, "2");
                }
            });
        }
    }

    private void TaskCreateOrderID(String goods_id, String real_name, String phone_mob, String booking_date, String booking_time, String site_type, String addr_id, String store_id, String coupon_id, String payment_code, String order_source) {
        RequestServerManager.getInstance().handleMethod((GBaseActivity) mContext, null, null, false,
                Constant.getRootUrl() + Constant.Action.Action_Order_Save, RequestServerManager.getInstance().
                        getRequestParams(Constant.Action.Action_Order_Save, goods_id, real_name, phone_mob, booking_date, booking_time, site_type, addr_id, store_id, coupon_id, payment_code, order_source), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result.getRetval()));
                        order_id = jsonObject.getString("order_id");
                        order_detailed = jsonObject.getString("detail_url");
                        if (payType.equals(payTypeAlipay)) {
                            TaskAlibabaPay(order_id, (GBaseActivity) mContext);
                            PayFlag = thisFlag;
                        } else if (payType.equals(payTypeWeiXinpay)) {
                            TaskWeixinPay(order_id, (GBaseActivity) mContext);
                            WXPayEntryActivity.OrderId = order_id;
                            WXPayEntryActivity.OrderUrl = order_detailed;
                            WXPayEntryActivity.WXPayFlag = thisFlag;
                        }
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {

                    }
                });
    }

    public static void TaskAlibabaPay(String order_id, final GBaseActivity gBaseActivity) {
        RequestServerManager.getInstance().handleMethod(gBaseActivity, null, null, false,
                Constant.getRootUrl() + Constant.Action.Action_Order_Pay_Alibaba, RequestServerManager.getInstance().
                        getRequestParams(Constant.Action.Action_Order_Pay_Alibaba, order_id), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                        AliPayBean aliPayBean = JSON.parseObject(JSON.toJSONString(result.getRetval()), AliPayBean.class);
                        pay(aliPayBean, gBaseActivity);
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {

                    }
                });
    }

    /**
     * call alipay sdk pay. 调用SDK支付
     */
    public static void pay(AliPayBean alibabaOrderInfo, final GBaseActivity gBaseActivity) {
        if (TextUtils.isEmpty(alibabaOrderInfo.getPartner()) || TextUtils.isEmpty(alibabaOrderInfo.getPrivatekey())
                || TextUtils.isEmpty(alibabaOrderInfo.getSeller())) {

          /*  new AlertDialog.Builder(mContext)
                    .setTitle("警告")
                    .setMessage("需要配置PARTNER | RSA_PRIVATE| SELLER")
                    .setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {
                                public void onClick(
                                        DialogInterface dialoginterface, int i) {
                                    //
                                    ((GBaseActivity)mContext).finish();
                                }
                            }).show();*/
            return;
        }
        // 订单
        String orderInfo = getOrderInfo(alibabaOrderInfo);

        // 对订单做RSA 签名
        String sign = sign(orderInfo, alibabaOrderInfo);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
            //sign="partner='2088601052577326'&seller_id='kzj_china@126.com'&out_trade_no='103010051362042'&subject='测试的商品'&body='该测试商品的详细描述'&total_fee='0.01'&notify_url='http://www.baidu.com'&service='mobile.securitypay.pay'&payment_type='1'&_input_charset='utf-8'&it_b_pay='30m'&return_url='m.alipay.com'";

        } catch (Exception e) {
            e.printStackTrace();
        }

        // 完整的符合支付宝参数规范的订单信息
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
                + getSignType();

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(gBaseActivity);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    public static Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);

                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();

                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        App.getInstance().showToast("支付成功");
                        OrderBean orderBean = new OrderBean();
                       // orderBean.setDetail_url(order_detailed);
                        orderBean.setOrder_id(order_id);
                        CloseActivityBean closeActivityBean = new CloseActivityBean();
                        closeActivityBean.setOrderBean(orderBean);
                        closeActivityBean.setIsSuccess(true);
                        closeActivityBean.setFromActivity(PayFlag);
                        EventBus.getDefault().post(closeActivityBean);
                        //跳入订单详情
/*                        Intent intent = new Intent((GBaseActivity)mContext, OrderSuccessActivity.class);
                        intent.putExtra("order_id", order_id);
                        setResult(RESULT_OK);
                        startActivity(intent);*/
                    } else {
                        OrderBean orderBean = new OrderBean();
                        //orderBean.setDetail_url(order_detailed);
                        orderBean.setOrder_id(order_id);
                        CloseActivityBean closeActivityBean = new CloseActivityBean();
                        closeActivityBean.setOrderBean(orderBean);
                        closeActivityBean.setIsSuccess(false);
                        EventBus.getDefault().post(closeActivityBean);
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            App.getInstance().showToast("支付结果确认中");
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误

                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    App.getInstance().showToast("检查结果为：" + msg.obj);

                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    /**
     * create the order info. 创建订单信息
     */
    public static String getOrderInfo(AliPayBean alibabaOrderInfo) {

        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + alibabaOrderInfo.getPartner() + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + alibabaOrderInfo.getSeller() + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + alibabaOrderInfo.getOrder_sn() + "\"";

        // 商品名称
        orderInfo += "&subject=" + "\"" + alibabaOrderInfo.getGoods_name() + "\"";

        // 商品详情
        orderInfo += "&body=" + "\"" + alibabaOrderInfo.getGoods_name() + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + alibabaOrderInfo.getOrder_amount() + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + alibabaOrderInfo.getNotify_url()
                + "\"";

        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        orderInfo += "&return_url=\"m.alipay.com\"";

        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
        // orderInfo += "&paymethod=\"expressGateway\"";

        return orderInfo;
    }

    /**
     * get the sign type we use. 获取签名方式
     */
    public static String getSignType() {
        return "sign_type=\"RSA\"";
    }

    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param content 待签名订单信息
     */
    public static String sign(String content, AliPayBean alibabaOrderInfo2) {
        return SignUtils.sign(content, alibabaOrderInfo2.getPrivatekey());
    }


    private static enum LocalRetCode {
        ERR_OK, ERR_HTTP, ERR_JSON, ERR_OTHER
    }

    public static void sendPayReq(WeiXinPayBean result, IWXAPI api) {

		/*	*//** 商家向财付通申请的商家id *//*
        @property (nonatomic, retain) NSString *partnerId;
		*//** 预支付订单 *//*
        @property (nonatomic, retain) NSString *prepayId;
		*//** 随机串，防重发 *//*
        @property (nonatomic, retain) NSString *nonceStr;
		*//** 时间戳，防重发 *//*
        @property (nonatomic, assign) UInt32 timeStamp;
		*//** 商家根据财付通文档填写的数据和签名 *//*
        @property (nonatomic, retain) NSString *package;
		*//** 商家根据微信开放平台文档对数据做的签名 *//*
        @property (nonatomic, retain) NSString *sign;*/
        PayReq req = new PayReq();
        //服务端返回的参数
        req.appId = result.getAppid();
        req.partnerId = result.getPartnerid();
        req.prepayId = result.getPrepayid();
        req.nonceStr = result.getNoncestr();
        req.timeStamp = result.getTimestamp();
        req.packageValue = "Sign=WXPay";
        //   req.sign =result.getSign();


  /*      req.appId = result.getAppid();
        req.nonceStr="c94d46f0bc3d745462172ecd21f39440";
        req.packageValue ="Sign=WXPay";
        req.partnerId = "1232904201";
        req.prepayId="120100100015112535";
        req.timeStamp= "1448390809";
        req.sign="bd20fd4ab2f484f81ce6b0a7609971b8b9d84384";*/

        //req.sign=sign;
        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        signParams.add(new BasicNameValuePair("appid", req.appId));
        signParams.add(new BasicNameValuePair("appkey", Constant.SystemContext.WXKey));
        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
        signParams.add(new BasicNameValuePair("package", req.packageValue));
        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));

        req.sign = genSign(signParams);
        // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
        api.sendReq(req);
    }

    private static String genSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        int i = 0;
        for (; i < params.size() - 1; i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append(params.get(i).getName());
        sb.append('=');
        sb.append(params.get(i).getValue());

        String sha1 = WeiXinUtil.sha1(sb.toString());

        return sha1;
    }

    public static void TaskWeixinPay(final String order_id, final GBaseActivity gBaseActivity) {
        RequestServerManager.getInstance().handleMethod(gBaseActivity, null, null, false,
                Constant.getRootUrl() + Constant.Action.Action_Order_Pay_WeiXin, RequestServerManager.getInstance().
                        getRequestParams(Constant.Action.Action_Order_Pay_WeiXin, order_id), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                        // api = WXAPIFactory.createWXAPI((GBaseActivity)mContext, Constant.SystemContext.WXID, true);

                        IWXAPI api = WXAPIFactory.createWXAPI(gBaseActivity, null);
                        api.registerApp(Constant.SystemContext.WXID);
                        WeiXinPayBean weiXinPayBean = JSON.parseObject(JSON.toJSONString(result.getRetval()), WeiXinPayBean.class);
                        sendPayReq(weiXinPayBean, api);
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {
                        WXPayEntryActivity.OrderId = order_id;
                    }
                });
    }
}
